<?php
/**
 * Created by PhpStorm.
 * User: wangjun
 * Date: 2016-10-28
 * Time: 13:35
 */
namespace Home\Controller;
use Think\Controller;

class WxController extends Controller{
    public function weixin(){
        if(isset($_GET["echostr"])){
            $this->valid();
        }else{
            $this->responseMsg();
        }
    }
    //URL接入验证
    public function valid() {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    //接收信息和回复消息
    public function responseMsg() {
        $user = D('user');
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postStr = file_get_contents('php://input');
        if (!empty($postStr)){
            require ("./Org/function/common.php");//引入回复详细模板
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            //如果post有提交,说明用户很公众号有互动,判断有注册就更改其互动时间
            if( $user->where("openid='{$fromUsername}'")->find()){
                D()->execute("update user set hdtime=$time where openid='{$fromUsername}'");
            }
            if($postObj->MsgType == 'event' && $postObj->Event == 'subscribe') { //关注事件,回复图文加客服接口
                $resultStr = sprintf($news['newses'], $fromUsername, $toUsername, $time,
                             $news['title1'],$news['picurl1'],$news['newsurl1'],
                             $news['title2'],$news['picurl2'],$news['newsurl2'],
                             $news['title3'],$news['picurl3'],$news['newsurl3'],
                             $news['title4'],$news['picurl4'],$news['newsurl4'],
                             $news['title5'],$news['picurl5'],$news['newsurl5'],
                             $news['title6'],$news['picurl6'],$news['newsurl6']);
                echo $resultStr;
                $access_token = access_token();
                $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
                $content = '请回复数字 1 进行身份验证';
                //使用url编码
                $content = urlencode($content);
                $content_arr = array('content' => "{$content}");
                $reply_arr = array('touser' => "{$fromUsername}", 'msgtype' => 'text', 'text' => $content_arr);
                //编码成json格式
                $post = json_encode($reply_arr);
                //url解码
                $post = urldecode($post);
                //dump($post);exit;
                 https_request($url,$post);

            }else if($postObj->MsgType == 'event' && $postObj->Event == 'unsubscribe'){//取消关注事件
                $user = D('user');
                if($user->where("openid='{$fromUsername}'")->find()){
                    $user->where("openid='{$fromUsername}'")->delete();
                }

            }else if($postObj->MsgType == 'event' && $postObj->Event == 'CLICK' && $postObj->EventKey == '委托指导'){ //自定义菜单点击事件回复图文
                $resultStr = sprintf($news['newses'], $fromUsername, $toUsername, $time,
                             $news['title1'],$news['picurl1'],$news['newsurl1'],
                             $news['title2'],$news['picurl2'],$news['newsurl2'],
                             $news['title3'],$news['picurl3'],$news['newsurl3'],
                             $news['title4'],$news['picurl4'],$news['newsurl4'],
                             $news['title5'],$news['picurl5'],$news['newsurl5'],
                             $news['title6'],$news['picurl6'],$news['newsurl6']);
                echo $resultStr;
            }else if($postObj->MsgType == 'event' && $postObj->Event == 'CLICK' && $postObj->EventKey == '自助查询'){ //自定义菜单一级点击事件回复图文
                $resultStr = sprintf($yjnews['newses'], $fromUsername, $toUsername, $time,
                    $yjnews['title1'],$yjnews['picurl1'],$yjnews['newsurl1'],
                    $yjnews['title2'],$yjnews['picurl2'],$yjnews['newsurl2'],
                    $yjnews['title3'],$yjnews['picurl3'],$yjnews['newsurl3'],
                    $yjnews['title4'],$yjnews['picurl4'],$yjnews['newsurl4'],
                    $yjnews['title5'],$yjnews['picurl5'],$yjnews['newsurl5'],
                    $yjnews['title6'],$yjnews['picurl6'],$yjnews['newsurl6']);
                echo $resultStr;
            }

            if(!empty( $keyword )){
                if($keyword == 1){   //回复数字1进行身份验证
                    if($user->where("openid='{$fromUsername}'")->find()){
                        $contentStr = '您已成功进行了身份验证,无需再次验证';
                        $resultStr = sprintf($tmp_arr['text'], $fromUsername, $toUsername, $time,$contentStr);
                        echo $resultStr;
                    }else{
                        $appid = C('APPID');
                        $appurlstr = C('APPURL').__CONTROLLER__;
                        $contentStr = "<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$appurlstr}/code&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'>点击链接进行身份验证</a>";
                        $resultStr = sprintf($tmp_arr['text'], $fromUsername, $toUsername, $time,$contentStr);
                        echo $resultStr;
                    }
                }
                //用户发送除了1以外任何内容都回复图文
                $resultStr = sprintf($news['newses'], $fromUsername, $toUsername, $time,
                             $news['title1'],$news['picurl1'],$news['newsurl1'],
                             $news['title2'],$news['picurl2'],$news['newsurl2'],
                             $news['title3'],$news['picurl3'],$news['newsurl3'],
                             $news['title4'],$news['picurl4'],$news['newsurl4'],
                             $news['title5'],$news['picurl5'],$news['newsurl5'],
                             $news['title6'],$news['picurl6'],$news['newsurl6']);
                echo $resultStr;

            }else{
                echo "Input something...";
            }
        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature() {
        $token = C('TOKEN');
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    //发送短信
    public function smscode(){
        //将需要的类引入
        require ("./Org/alidayu/TopSdk.php");
        $appkey = C('ALIAPPKEY');//你的App key
        $secret = C('ALISECRETKEY');//你的App Secret:

        $c = new \TopClient;
        $c->appkey = $appkey;
        $c->secretKey = $secret;
        $tel = I('get.tel');
        $sum = rand(100000,999999);
        session($tel.'code',$sum);//把生成的随机数存进session
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend("123456");//确定发给的是哪个用户，参数为用户id
        $req->setSmsType("normal");
        /*
        进入阿里大鱼的管理中心找到短信签名管理，输入已存在签名的名称，这里是身份验证。
        */
        $req->setSmsFreeSignName("身份验证");
        $req->setSmsParam("{\"sum\":\"{$sum}\",\"product\":\"神舟软件\"}");
        //这里设定的是发送的短信内容：验证码${code}，您正在进行${product}身份验证，打死不要告诉别人哦！”
        $req->setRecNum($tel);//参数为用户的手机号码
        $req->setSmsTemplateCode("SMS_25140121");
        $resp = $c->execute($req);
        $this->ajaxReturn($resp);

    }
    //验证手机
    public function yztel(){
        $tel = I('post.tel');
        $personnel = D('personnel');
        $user= D('user');
        if(!$personnel->where("tel=$tel")->find()){
            $this->ajaxReturn(1);
        }elseif($user->where("tel=$tel")->find()){
            $this->ajaxReturn(2);
        }else{
            $this->ajaxReturn(3);
        }
    }

    //身份验证注册
    public function authentication(){
        $openid = I('post.openid');
        $tel = I('post.tel');
        $user = D('user');
        $time = time();
        if($user->where("tel='{$tel}'")->find()){
            $this->ajaxReturn('ok');
        }else{
            if(!empty($openid) && !empty($tel)){
                if(D()->execute("insert into user values (null,'{$openid}','{$tel}',$time)")){
                    $this->ajaxReturn(true);
                }else{
                    $this->ajaxReturn(false);
                }
            }
        }
    }

    //检查短信验证码是否正确
    public function checksms(){
        $code = I('get.code');
        $tel = I('get.tel');
        $sessioncode =  session($tel.'code');
        if($code == $sessioncode){
            session($tel.'code',null);
            $this->ajaxReturn(true);
        }else{
            $this->ajaxReturn(false);
        }
    }

    //回复数字1发送短信进行网页授权
    public function code(){
        if(isset($_GET['code'])){
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info,true);
            $openid = $info['openid'];
            $this->assign('openid',$openid);
            $this->display('sms');
        }else{
            $this->error('code获取失败');
        }
    }

    //我的委托网页授权
    public function consign(){
        if(isset($_GET['code'])) {
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info, true);
            $openid = $info['openid'];
            $this->redirect('Wx/weituo', array('openid' => $openid));
        }else{
            $this->error('no code');
        }
    }

    //我的委托列表
    public function weituo(){
        $openid = I('get.openid');
        $ks = I('get.ks')?strtotime(I('get.ks')):'';
        $js = I('get.js')?strtotime(I('get.js')):'';
        $user = D('user');
        $schedule = D('schedule');
        $personnel = D('personnel');
        if ($info = $user->where("openid='{$openid}'")->find()) {
            $tel = $info['tel'];
            if(!$list = $personnel->field('requester')->where("tel='{$tel}'")->find()){
                $this->assign('str','抱歉,暂未查到跟您相关的委托单位');
                $this->display('tishi');
            }else{
                $requester = $list['requester'];
                if($requester != 'admin'){
                    $where['requester'] = $requester;
                }
                if($ks && $js){
                    $where['wtsj'] = array('between',"$ks,$js");
                }elseif($ks){
                    $where['wtsj'] = array('egt',$ks);
                }elseif($js){
                    $where['wtsj'] = array('elt',$js);
                }else{
                    $mrtime = time()-(3600*24*90);
                    $where['wtsj'] = array('egt',$mrtime);
                }
                $length = 15;//每页显示条数
                $data = $this->infoPage($schedule,$where,$length);
                $this->assign(array(
                    'list' => $data['list'],
                    'page' => $data['page_str'],
                    'jstime' => date('Y-m-d',time()),
                    'kstime' => date('Y-m-d',$mrtime),
                    'requester' => $requester,
                    'openid' => $openid,
                    'firstRow' => $data['firstRow']
                ));
                $this->display('consign');
            }
        } else {
            $this->assign('str','抱歉,您还没有进行身份注册!请注册成功后再进行查询.');
            $this->display('tishi');
        }
    }

    //进度搜索网页授权
    public function jindu(){
        if(isset($_GET['code'])) {
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info, true);
            $openid = $info['openid'];
            $this->redirect('Wx/jindu2', array('openid' => $openid));
        }else{
            $this->error('no code');
        }
    }

    //进度搜索页面
    public function jindu2(){
        $openid = I('openid');
        $dpasum = I('get.dpasum');
        $user = D('user');
        $schedule = D('schedule a');
        $personnel = D('personnel');
        if (!$info = $user->where("openid='{$openid}'")->find()) {
            $this->assign('str','抱歉,您还没有进行身份注册!请注册成功后再进行查询.');
            $this->display('tishi');
        }else{
            $tel = $info['tel'];
            if(!$list = $personnel->field('requester')->where("tel='{$tel}'")->find()){
                $this->assign('str','抱歉,暂未查到跟您相关的委托单位');
                $this->display('tishi');
            }else{
                $requester = $list['requester'];
                if($requester != 'admin'){
                    $where['a.requester'] = $requester;
                }
                if($dpasum){
                    $where['a.dpasum'] = array('like',"%".$dpasum."%");
                }else{
                    $mrtime = time()-(3600*24*90);
                    $where['wtsj'] = array('egt',$mrtime);
                }
                $coun = $schedule->where($where)->count();
                $page = new \Think\Page($coun,1);
                $page->setConfig('prev','上一页');
                $page->setConfig('next','下一页');
                $data = $schedule->field('a.*,b.dpasum dpa ,b.givename,b.givetime,b.givelocation,b.getname,b.gettime,b.getlocation')
                    ->join('LEFT JOIN __CONNECT__ b ON a.dpasum=b.dpasum')
                    ->where($where)
                    ->limit($page->firstRow,$page->listRows)
                    ->order('wtsj desc')->select();
                //dump($data);exit;
                $this->assign(array(
                    'list' => $data,
                    'page' => $page->show(),
                    'openid' => $openid
                ));
                $this->display('seachlist');
            }
        }
    }

    //联系我们
    public function lxwm(){
        $time = time();
        $this->assign('time',$time);
        $this->display();
    }

    /**
     * 封装分页函数
     * @param $table
     * @param $where
     * @param $length
     * @return array
     */
    public function infoPage($table,$where,$length)
    {
        $coun = $table->where($where)->count();
        $page = new  \Think\Page($coun, $length);
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $page_str = $page->show();
        $list = $table->where($where)->limit($page->firstRow,$page->listRows)->order('wtsj desc')->select();
        $data = [
            'coun' => $coun,
            'list' => $list,
            'page_str' => $page_str,
            'firstRow' => $page->firstRow
        ];
        return $data;
    }

    //错误提示
    public function tishi(){
        $this->display();
    }
    //测试上传素材
    public function load(){
        $access_token = access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token={$access_token}";
        $img = ROOT.'/Upload/wximg/1478481672.jpg';
        //$data = array("media" => "@".$img);
        $data = '{"type":"image","offset":0,"count":20}';
        $info = https_request($url);
        $arr_info = json_decode($info,true);
        dump($arr_info);
    }

    //日期查询任务ajax分
    public function ajaxtime(){
        $kstime = I('kstime')?strtotime(I('kstime')):'';
        $jstime = I('kstime')?strtotime(I('jstime')):'';
        $requester = I('requester');
        $status = I('status')?I('status'):'';
        if(!empty($kstime) && !empty($jstime)){
            $schedule = D('schedule');
            $where['wtsj'] = array('between',"$kstime,$jstime");
            if($requester != 'admin'){
                $where['requester'] = $requester;
            }
            if(!empty($status)){
                $where['status'] = $status;
            }
            $coun = $schedule->where($where)->count();
            $page = new \Think\Page($coun,15);
            $page->setConfig('prev','上一页');
            $page->setConfig('next','下一页');
            $list = $schedule->field('id,dpasum,wtsj,status,end')->where($where)->limit($page->firstRow,$page->listRows)
                ->order('wtsj desc')->select();
            foreach($list as $k=>$v){
                $list[$k]['wtsj']= date('Y-m-d',$v['wtsj']);
            }
            $data = [
                'list' => $list,
                'page_str' => $page->show(),
                'firstRow' => $page->firstRow
            ];
            $this->ajaxReturn($data);
        }
    }

    //详细查询网页授权获取code
    public function detail(){
        if(isset($_GET['code'])) {
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info, true);
            $openid = $info['openid'];
            $this->redirect('Wx/exact', array('openid' => $openid));
        }else{
            $this->error('no code');
        }
    }

    //条件查询页面
    public function exact(){
        $openid = I('openid');
        $user = D('user');
        $personnel = D('personnel');
        if(!$info = $user->where("openid='{$openid}'")->find()){
            $this->assign('str','抱歉,您还没有进行身份注册!请注册成功后再进行查询.');
            $this->display('tishi');
        }else{
            $tel = $info['tel'];
            if(!$list = $personnel->where("tel='{$tel}'")->find()){
                $this->assign('str','抱歉,暂未查到跟您相关的委托单位');
                $this->display('tishi');
            }else{
                $requester = $list['requester'];
                $this->assign('requester',$requester);
                $this->assign('openid',$openid);
                $this->display();
            }
        }
    }

    //多条件查询后的结果页面
    public function jingque(){
        $dpasum = I('get.dpasum')?ucfirst(I('get.dpasum')):''; //把首字母转大写
        $gxsum = I('get.gxsum')?strtoupper(I('get.gxsum')):''; //把小写转大写
        $xhtype = I('get.xhtype')?strtoupper(I('get.xhtype')):'';//把小写转大写
        $norm = I('get.norm')?strtoupper(I('get.norm')):'';//把小写转大写
        $batch = I('get.batch')?strtoupper(I('get.batch')):'';//把小写转大写
        $zlgrage = I('get.zlgrage')?strtoupper(I('get.zlgrage')):'';//把小写转大写
        $output = I('get.output')?strtoupper(I('get.output')):'';//把小写转大写
        $kssj = I('get.kssj')?strtotime(I('get.kssj')):'';//把小写转大写
        $jssj = I('get.jssj')?strtotime(I('get.jssj')):'';//把小写转大写
        $openid = I('get.openid');
        $requester = I('get.requester');
        $arr = [];
        //模糊查询
        if($dpasum) {
            $arr['a.dpasum'] = array('like',"%".$dpasum."%");
         }
        if($gxsum){
            $arr['gxsum'] = array('like',"%".$gxsum."%");
        }
        if($xhtype){
            $arr['xhtype'] = array('like',"%".$xhtype."%");
        }
        if($norm){
            $arr['norm'] = array('like',"%".$norm."%");
        }
        if($batch){
            $arr['batch'] = array('like',"%".$batch."%");
        }
        if($zlgrage){
            $arr['zlgrage'] = array('like',"%".$zlgrage."%");
        }
        if($output){
            $arr['output'] = array('like',"%".$output."%");
        }
        //判断时间条件
        if($kssj && $jssj){
            $arr['wtsj'] = array('between',"$kssj,$jssj");
        }elseif($kssj){
            $arr['wtsj'] = array('egt',$kssj);
        }elseif($jssj){
            $arr['wtsj'] = array('elt',$jssj);
        }
        if($requester != 'admin'){
            $arr['a.requester'] =$requester;
        }
        //dump($arr);
        $schedule = D('schedule a');
        $coun = $schedule->where($arr)->count();
        $page = new \Think\Page($coun,1);
        $page->setConfig('prev','上一页');
        $page->setConfig('next','下一页');
        //连表查询交接情况
        $data = $schedule->field('a.*,b.dpasum dpa ,b.givename,b.givetime,b.givelocation,b.getname,b.gettime,b.getlocation')
                         ->join('LEFT JOIN __CONNECT__ b ON a.dpasum=b.dpasum')
                         ->where($arr)
                         ->limit($page->firstRow,$page->listRows)
                         ->order('wtsj desc')->select();
        //dump($data);exit;
        $this->assign(array(
            'list' => $data,
            'page' => $page->show(),
            'openid' => $openid,
        ));
        $this->display();
    }

    //代取报告网页授权
    public function wait(){
        /*通过code获取openid*/
        if(isset($_GET['code'])){
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info, true);
            $openid = $info['openid'];
            $this->redirect('Wx/swait', array('openid' => $openid));
        }else{
            $this->error('no code');
        }
    }
    public function swait(){
        $openid = I('get.openid');
        $ks = I('get.ks')?strtotime(I('get.ks')):'';
        $js = I('get.js')?strtotime(I('get.js')):'';
        $user = D('user');
        $personnel = D('personnel');
        $schedule = D('schedule');
        $connectmodel = D('connect');
        if(!$users = $user->where("openid='{$openid}'")->find()){ //验证有无注册
            $this->assign('str','抱歉,您还没有进行身份注册!请注册成功后再进行查询.');
            $this->display('tishi');
        }else{
            $tel = $users['tel'];
            if(!$perinfo = $personnel->field('requester')->where("tel='{$tel}'")->find()){ //验证信息是否吻合
                $this->assign('str','抱歉,暂未查到跟您相关的委托单位');
                $this->display('tishi');
            }else{
                $requester = $perinfo['requester'];
                if($requester != 'admin'){
                    $where['requester'] = $requester;
                }
                if($ks && $js){
                    $where['wtsj'] = array('between',"$ks,$js");
                }elseif($ks){
                    $where['wtsj'] = array('egt',$ks);
                }elseif($js){
                    $where['wtsj'] = array('elt',$js);
                }else{
                    $mrtime = time()-(3600*24*90);
                    $where['wtsj'] = array('egt',$mrtime);
                }
                if($con_res = $connectmodel->field('dpasum')->select()){ //从交接表中取出dpasum,
                    $dpasuminfo = array_column($con_res,'dpasum');
                    $where['dpasum'] = array('not in' ,$dpasuminfo);//进度表中不存在这些dpasum就为未取报告
                }
                $where['status'] = '已完成';
                $length = 15;//每页显示条数
                $data = $this->infoPage($schedule,$where,$length);
                $this->assign(array(
                    'list' => $data['list'],
                    'page' => $data['page_str'],
                    'jstime' => date('Y-m-d',time()),
                    'kstime' => date('Y-m-d',$mrtime),
                    'requester' => $requester,
                    'openid' => $openid,
                    'firstRow' => $data['firstRow']
                ));
                $this->display();

            }
        }
    }

    //未取报告点击dpa号跳转页面
    public function seach_wq(){
        if(IS_GET){
            $dpasum = I('dpasum');
            $schedule = D('schedule');
            $where['dpasum'] = $dpasum;
            $info = $schedule->where($where)->find();
            if (!$info ) {
                $this->error('抱歉,此报告号没找到');
            }else{
                $this->assign('info',$info);
            }
            $this->display();
        }
    }

    //已取报告网页授权获取code
    public function complete(){
        if(isset($_GET['code'])) {
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info, true);
            $openid = $info['openid'];
            $this->redirect('Wx/wcdpa', array('openid' => $openid));
        }else{
            $this->error('no code');
        }
    }

    //已取报告页面
    public function wcdpa(){
        $openid = I('get.openid');
        $ks = I('get.ks')?strtotime(I('get.ks')):'';
        $js = I('get.js')?strtotime(I('get.js')):'';
        $user = D('user');
        $personnel = D('personnel');
        $connectmodel = D('connect');
        if(!$users = $user->where("openid='{$openid}'")->find()){
            $this->assign('str','抱歉,您还没有进行身份注册!请注册成功后再进行查询.');
            $this->display('tishi');
        }else{
            $tel = $users['tel'];
            if(!$perinfo = $personnel->field('requester')->where("tel='{$tel}'")->find()){
                $this->assign('str','抱歉,暂未查到跟您相关的委托单位');
                $this->display('tishi');
            }else{
                $requester = $perinfo['requester'];
                $where = array();
                if($requester != 'admin'){
                    $where['requester'] = $requester;
                }
                if($ks && $js){
                    $where['gettime'] = array('between',"$ks,$js");
                }elseif($ks){
                    $where['gettime'] = array('egt',$ks);
                }elseif($js){
                    $where['gettime'] = array('elt',$js);
                }else{
                    $mrtime = time()-(3600*24*90);
                    $where['gettime'] = array('egt',$mrtime);
                }
                $coun = $connectmodel->where($where)->count();
                $page = new \Think\Page($coun,15);
                $page->setConfig('prev','上一页');
                $page->setConfig('next','下一页');
                $data = $connectmodel->field('dpasum,getname,gettime,givename')->where($where)
                                     ->limit($page->firstRow,$page->listRows)->order('gettime desc')->select();
                //dump($data);exit;
                $this->assign(array(
                    'list' => $data,
                    'page' => $page->show(),
                    'jstime' => date('Y-m-d',time()),
                    'kstime' => date('Y-m-d',$mrtime),
                    'requester' => $requester,
                    'openid' => $openid,
                    'firstRow' => $data['firstRow']
                ));
                $this->display();
            }
        }
    }

    //ajax已取报告按时间查询
    public function ajaxconntime(){
        $kstime = I('get.kstime')?strtotime(I('get.kstime')):'';
        $jstime = I('get.jstime')?strtotime(I('get.jstime')):'';
        $jstime = $jstime+(3600*24-1);
        $requester = I('get.requester');
        $connectmodel = D('connect');
        $where = [];
        if($kstime && $jstime){
            $where['gettime'] = array('between',"$kstime,$jstime");
        }elseif($kstime){
            $where['gettime'] = array('egt',$kstime);
        }elseif($jstime){
            $where['gettime'] = array('elt',$jstime);
        }
        if($requester != 'admin'){
            $where['requester'] = $requester;
        }
        $coun = $connectmodel->where($where)->count();
        $page = new \Think\Page($coun,15);
        $page->setConfig('prev','上一页');
        $page->setConfig('next','下一页');
        $data = $connectmodel->field('dpasum,getname,gettime,givename')->where($where)
            ->limit($page->firstRow,$page->listRows)->order('gettime desc')->select();
        foreach($data as $k=>&$v){
            $v['gettime'] = date('Y-m-d',$v['gettime']);
        }
        $this->ajaxReturn(array(
            'list' => $data,
            'page_str' => $page->show(),
            'firstRow' => $page->firstRow,
        ));
    }

    //已取报告点击dpa报告号跳转页面
    public function seach_wc(){
        if(IS_GET){
            $dpasum = I('dpasum');
            $schedule = D('schedule a');
            $where['a.dpasum'] = $dpasum;
            $info = $schedule->field('a.*,b.dpasum dpa ,b.givename,b.givetime,b.givelocation,b.getname,b.gettime,b.getlocation')
                             ->join('LEFT JOIN __CONNECT__ b ON a.dpasum=b.dpasum')
                             ->where($where)->find();
            if (!$info ) {
                $this->error('抱歉,此报告号没找到');
            }else{
                $this->assign('info',$info);
            }
            $this->display();
        }
    }

    //扫一扫 网页授权
    public function scan(){
        //验证code获取openid
        if(isset($_GET['code'])){
            $appid = C('APPID');
            $secret = C('APPSECRET');
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
            $info = https_request($url);
            $info = json_decode($info, true);
            $openid = $info['openid'];
            //通过openID验证用户身份,是否有扫一扫权限
            $user = D('user');
            $personnel = D('personnel');
            if(!$users = $user->where("openid='{$openid}'")->find()){
                $this->assign('str','抱歉,您还没有进行身份注册!请注册成功后再进行操作.');
                $this->display('tishi');
            }else{
                $tel = $users['tel'];
                if($requesters = $personnel->field('requester')->where("tel='{$tel}'")->find()){
                    $req = $requesters['requester']; //扫描人委托单位
                }else{
                    $this->assign('str','抱歉,人员信息表未查到您的信息,请查证后再进行操作.');
                    $this->display('tishi');
                }
                //网页jssdk config注入签名验证
                $ticket = get_ticket();
                $noncestr =md5(time());
                $time = time();
                $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $str1 = "jsapi_ticket={$ticket}&noncestr={$noncestr}&timestamp={$time}&url={$url}";
                $singature = sha1($str1);
                $this->assign(array(    //签名验证
                    'noncestr' => $noncestr,
                    'time' => $time,
                    'singature' => $singature,
                ));
                $this->assign(array(   //数据
                    'requester' => $req,
                    'tel' => $tel,
                    'openid' => $openid
                ));
                $this->display();
            }
        }else{
            $this->error("网页授权失败");
        }
    }

    //ajax提交扫描的数据同步二维码数据进行验证
    public function ajaxverify(){
        $data = I('post.data');
        $list = explode('@@',$data);
        if($list[0] != 'schedule' ){  //判断扫描的二维码的表名不是schedule返回错误
            $this->ajaxReturn('tablenamefalil');
        }else{ //判断如果是schedule,把拆分的数组存入redis
            if(count($list) != 13){  //判断表面的字段数量
                $this->ajaxReturn('schedulecountfail');
                //判断表的字段
            }elseif($list[1] != 'id' || $list[3] != 'dpasum' || $list[5] != 'status' || $list[7] != 'end' || $list[9] != 'assess' || $list[11] != 'remark'){
                $this->ajaxReturn('schedulefieldfail');
            }else{
                $arr = array(
                    'id' => $list[2],
                    'dpasum' => (string)$list[4],
                    'status' => (string)$list[6],
                    'end' => (string)$list[8],
                    'assess' => (string)$list[10],
                    'remark' => (string)$list[12]
                );
                $where['dpasum'] = $arr['dpasum'];
                $schedulemodel = D('schedule');
                if(!$schinfo = $schedulemodel->field('requester,ts_status')->where($where)->find()){
                    $this->ajaxReturn('dpasumfail');
                }else{
                    if(false === $schedulemodel->where($where)->save($arr)){
                        $this->ajaxReturn('savefail');
                    }else{
                        $this->ajaxReturn(array(
                            'type' => 'ok',
                            'ts_status' => $schinfo['ts_status'],
                            'requester' => $schinfo['requester'],
                            'dpasum' => $arr['dpasum']
                        ));
                    }
                }
            }
        }
    }
    //ajax扫码插入数据库成功之后推送dpa信息
   public function ajax_push_dpa(){
       $schedule = D('schedule');
       $requester = I('post.requester');
       $dpasum = I('post.dpasum');
       $schedule->push_dpa($requester,$dpasum);
       if($schedule->execute("update schedule set ts_status=1 where dpasum='$dpasum'")){
           $this->ajaxReturn('ok');
       }else{
           $this->ajaxReturn('fail');
       }
   }
    //ajax插入connect交接表并推送信息
    public function ajaxinsertconnect(){
        $dpasum = I('post.dpasum');
        $givename = I('post.givename');
        $givetime = I('post.givetime');
        $givelocation = I('post.givelocation');
        $getname = I('post.getname');
        $gettime = I('post.gettime');
        $getlocation = I('post.getlocation');
        $tel = I('post.tel');
        $openid = I('post.openid');
        $requester = I('post.requester');
        $connectmodel = D('connect');
        if($connectmodel->add(array(
            'dpasum' => $dpasum,
            'givename' => $givename,
            'givetime' => $givetime,
            'givelocation' => $givelocation,
            'getname' => $getname,
            'gettime' => $gettime,
            'getlocation' => $getlocation,
            'tel' => $tel,
            'requester' => $requester
        ))){
            $access_token = access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
            $content = 'DPA报告('.$dpasum .')已完成交接,请进入已取报告查阅';
            //使用url编码
            $content = urlencode($content);
            $content_arr = array('content' => "{$content}");
            $reply_arr = array('touser' => $openid, 'msgtype' => 'text', 'text' => $content_arr);
            //编码成json格式
            $post = json_encode($reply_arr);
            //url解码
            $post = urldecode($post);
            //dump($post);exit;
            $info = https_request($url,$post);
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    //扫描dpa报告交接
    public function qrcode(){
        $result = I('post.result');
        $requester = I('post.requester'); //扫描人的委托单位
        $data = explode('@@',$result);
        $connectmodel = D('connect');
        $schedulemodel = D('schedule');
        $dpasum = $data[4];
        $where['dpasum'] = $dpasum;
        $conninfo = $connectmodel->where($where)->find();
        $schinfo = $schedulemodel->field('requester,status')->where($where)->find(); //获取扫描的二维码的委托单位和状态
        if($data[0] != 'savedpa' && $data[0] != 'connect'){ //交接二维码第一个字段必须是savedpa或者是connect
            $this->ajaxReturn('tablenamefalil');
        }elseif($data[0] == 'savedpa'){ //判断管理员扫描的交接码
            if($requester != 'admin'){ //判断扫描二维码人的委托单位,只能是管理人员才能扫描schedule的二维码
                $this->ajaxReturn('purviewfail');
            }elseif($data[3] != 'dpasum'){
                $this->ajaxReturn('dpafieldfail');
            }else{
                if($conninfo){ //判断二维码的dpa报告是否已经完成交接
                    $this->ajaxReturn('connectok');
                }elseif(!$schinfo){ //判断dpa号是否存在
                    $this->ajaxReturn('dpasumfail');
                }else{
                    if($schinfo['status'] != '已完成' ){
                        $this->ajaxReturn('statusfial');
                    }else{
                        $this->ajaxReturn(array(
                            'ok' => 1,
                            'dpasum' => $dpasum
                        ));
                    }
                }
            }
        }elseif($data[0] == 'connect'){
            if($schinfo['requester'] != $requester){ //检测扫描交接二维码的人员的单位必须是dpa报告里的单位
                $this->ajaxReturn('reqfail');
            }elseif(($data[1] != 'givename')|| ($data[3] != 'dpasum') || ($data[5] != 'givetime') || ($data[7] != 'location') || ($data[9] != 'openid')){
                $this->ajaxReturn('connectfieldfail'); //检测交接二维码的字段信息
            }elseif($conninfo) {   //判断二维码的dpa报告是否已经完成交接
                $this->ajaxReturn('connectok');
            }else{
                $arr = array('givename'=>$data[2],'dpasum'=>$dpasum,'requester'=>$schinfo['requester'],'givetime'=>$data[6],'location'=>$data[8],'openid'=>$data[10]);
                $redis = linkredis();
                $redissetconnectname = 'connect' . $dpasum . time();
                $redis->set($redissetconnectname, serialize($arr));
                $redis->expire($redissetconnectname, 600);
                $this->ajaxReturn(array(
                    'ok' => 2,
                    'key' => $redissetconnectname
                ));
            }
        }
    }
//管理员扫描报告首页交接码生成交接二维码
    public function generate(){
        $tel = I('get.tel');
        $wzlocation = I('get.wzlocation');
        $dpasum = I('get.dpasum');
        $schedulemodel = D('schedule');
        $personnelmodel = D('personnel a');
        $location = location($wzlocation); //调用百度车联网API获取省市区
        $schinfo = $schedulemodel->field('requester')->where("dpasum='{$dpasum}'")->find(); //查出dpa报告的委托单位
        $requester = $schinfo['requester'];
        $perinfo = $personnelmodel->field('a.client,b.openid')
            ->join('left join user b on a.tel=b.tel')
            ->where("a.tel='{$tel}'")->find();//查出当前扫描交接码人员的姓名
        $givename = $perinfo['client'];
        $openid = $perinfo['openid']; //查出生成二维码人员的openid,一并存在二维码里
        $givetime = time();
        $save_path = C('SAVEQRCODEPATH');
        $showqrcode_path = C('APPURL') . __ROOT__ . C('SHOWQRCODEPATH');//二维码显示路径
        $qr_data = "connect@@givename@@$givename@@dpasum@@$dpasum@@givetime@@$givetime@@location@@$location@@openid@@$openid";//拼接二维码参数
        if ($filename = createQRcode($save_path, $qr_data)) { //调用二维码生成类
            $this->assign(array(
                'showqrcode_path' => $showqrcode_path . $filename,
                'dpasum' => $dpasum,
                'requester' => $requester
            ));
            $this->display();
        } else {
            $this->error('二维码生成失败!');
        }
    }
//用户扫描管理员生成的交接码生成确认页面
    public function connverify(){
        $key = I('get.key');
        $location = I('get.wzlocation');
        $tel = I('get.tel');
        $wzlocation = location($location);
        $redis = linkredis();
        if(!$redisinfo = unserialize($redis->get($key))){
            $this->error('抱歉,缓存数据已失效,请重新扫描');
        }else{
            $personnelmodel = D('personnel');
            $perinfo = $personnelmodel->where("tel='{$tel}'")->find();
            $getname = $perinfo['client'];
            $gettime = time();
            $this->assign(array(
                'dpasum' => $redisinfo['dpasum'],
                'requester' => $redisinfo['requester'],
                'givename' => $redisinfo['givename'],
                'givetime' => $redisinfo['givetime'],
                'givelocation' => $redisinfo['location'],
                'getname' => $getname,
                'gettime' => $gettime,
                'tel' => $tel,
                'getlocation' => $wzlocation,
                'openid' => $redisinfo['openid']
            ));
            $this->display();
        }
    }
}

